<template>
  <div class="rescue-submit">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>救助信息</h1>
        <p>发现流浪宠物？请填写以下信息帮助它们找到温暖的家</p>
      </div>
      <!-- 救助信息表单 -->
      <div class="form-container">
        <el-form ref="rescueForm" :model="form" :rules="rules" label-width="120px" class="rescue-form">
          <!-- 基本信息 -->
          <div class="form-section">
            <h2>基本信息</h2>

            <el-form-item label="救助标题" prop="title" required>
              <el-input v-model="form.title" placeholder="请输入救助信息标题" maxlength="50" show-word-limit />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="动物种类" prop="species" required>
                  <el-select v-model="form.species" placeholder="请选择" style="width: 100%">
                    <el-option label="狗" value="狗" />
                    <el-option label="猫" value="猫" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="体型大小" prop="size">
                  <el-select v-model="form.size" placeholder="请选择" style="width: 100%">
                    <el-option label="小型" value="小型" />
                    <el-option label="中型" value="中型" />
                    <el-option label="大型" value="大型" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="估计年龄" prop="age">
                  <el-input v-model="form.age" placeholder="请输入估计年龄" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="form.gender" placeholder="请选择" style="width: 100%">
                    <el-option label="雄性" value="雄性" />
                    <el-option label="雌性" value="雌性" />
                    <el-option label="不确定" value="不确定" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 发现地点 -->
          <div class="form-section">
            <h2>发现地点</h2>

            <el-form-item label="详细地址" prop="location" required>
              <el-input v-model="form.location" placeholder="请输入发现宠物的详细地址" />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="发现时间" prop="foundDate" required>
                  <el-date-picker v-model="form.foundDate" type="datetime" placeholder="选择发现时间" style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="紧急程度" prop="urgency" required>
                  <el-select v-model="form.urgency" placeholder="请选择" style="width: 100%">
                    <el-option label="一般" value="一般" />
                    <el-option label="紧急" value="紧急" />
                    <el-option label="非常紧急" value="非常紧急" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 健康状况 -->
          <div class="form-section">
            <h2>健康状况</h2>

            <el-form-item label="健康状况" prop="healthStatus" required>
              <el-select v-model="form.healthStatus" placeholder="请选择" style="width: 100%">
                <el-option label="良好" value="良好" />
                <el-option label="受伤" value="受伤" />
                <el-option label="生病" value="生病" />
                <el-option label="危重" value="危重" />
              </el-select>
            </el-form-item>

            <el-form-item label="详细描述" prop="description">
              <el-input type="textarea" v-model="form.description" placeholder="请详细描述宠物的外观特征、健康状况、行为表现等信息" :rows="4"
                maxlength="500" show-word-limit />
            </el-form-item>

            <el-form-item label="伤病情况" prop="injuries">
              <el-input type="textarea" v-model="form.injuries" placeholder="如有外伤或疾病症状，请详细描述" :rows="3" maxlength="300"
                show-word-limit />
            </el-form-item>
          </div>

          <!-- 照片上传 -->
          <div class="form-section">
            <h2>照片上传</h2>

            <el-form-item label="宠物照片" prop="imageList">
              <el-upload class="photo-uploader" action="/api/file/upFile" list-type="picture-card" :file-list="form.imageList"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload" :on-success="handleAvatarSuccess"
                :limit="5" :on-exceed="handleExceed" accept="image/*" multiple>
                <i class="el-icon-plus"></i>
              </el-upload>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb，最多5张</div>
            </el-form-item>
          </div>

          <!-- 联系信息 -->
          <div class="form-section">
            <h2>联系信息</h2>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactName">
                  <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="最佳联系时间" prop="contactTime">
              <el-input v-model="form.contactTime" placeholder="例如：工作日 9:00-18:00" />
            </el-form-item>
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <el-button type="primary" @click="submitRescue" :loading="submitting" size="large">
              {{ form.id ? '更新救助信息' : '发布救助信息' }}
            </el-button>
            <el-button @click="goBack">
              取消
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { submitRescue, updateRescue, getRescueDetail } from '@/api/rescue-info'
import { mapGetters } from 'vuex'
export default {
  name: 'RescueSubmit',
  computed: {
    ...mapGetters(['user'])
  },
  data() {
    return {
      submitting: false,
      form: {
        id: undefined,
        title: '',
        species: '',
        size: '',
        age: '',
        gender: '',
        location: '',
        foundDate: '',
        urgency: '',
        healthStatus: '',
        description: '',
        injuries: '',
        imageList: [],
        contactName: '',
        contactPhone: '',
        contactTime: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入救助标题', trigger: 'blur' },
          { min: 5, max: 50, message: '标题长度在 5 到 50 个字符', trigger: 'blur' }
        ],
        species: [
          { required: true, message: '请选择动物种类', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入发现地址', trigger: 'blur' }
        ],
        foundDate: [
          { required: true, message: '请选择发现时间', trigger: 'change' }
        ],
        urgency: [
          { required: true, message: '请选择紧急程度', trigger: 'change' }
        ],
        healthStatus: [
          { required: true, message: '请选择健康状况', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入详细描述', trigger: 'blur' },
          { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        imageList: [
          { required: true, message: '请上传宠物照片', trigger: 'change' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    goBack() {
      this.$router.push('/my-rescues')
    },
    // Element UI 上传组件相关方法
    handlePictureCardPreview(file) {
      this.$alert(`<img src="${file.url}" style="width: 100%">`, '图片预览', {
        dangerouslyUseHTMLString: true
      })
    },

    // 上传成功后的回调
    handleAvatarSuccess(res, file) {
      // file.url = URL.createObjectURL(file.raw)
      this.form.imageList.push(res.data)
    },

    handleRemove(file, fileList) {
      this.form.imageList = fileList
    },

    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt500K = file.size / 1024 < 5000

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt500K) {
        this.$message.error('上传图片大小不能超过 500KB!')
        return false
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },

    async submitRescue() {
      try {
        // 使用Element UI的表单验证
        await this.$refs.rescueForm.validate()
        this.submitting = true
        // 提交表单数据
        this.form.image = this.form.imageList.join(',')
        this.form.userId = this.user.id
        this.form.userName = this.user.name
        const res = await (this.form.id ? updateRescue(this.form) : submitRescue(this.form))
        if (res.code === 200) {
          this.$message.success('救助信息发布成功！')
          this.$router.push('/my-rescues')
        } else {
          this.$message.error('发布失败，请重试')
        }
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          this.$message.error('发布失败，请重试')
        }
      } finally {
        this.submitting = false
      }
    },
    // 初始化表单数据
    async initFormData() {
      if (this.$route.query.edit) {
        try {
          const res = await getRescueDetail(this.$route.query.edit)
          if (res.code === 200) {
            this.form = res.data
            this.form.imageList = this.form.image.split(',')
          }
        } catch (error) {
          this.$message.error('获取详情失败，请重试')
        }
      }
    },
  },

  mounted() {
    this.initFormData() 
  }
}
</script>

<style scoped>
.rescue-submit {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 20px 0;
}


.form-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.rescue-form {
  padding: 40px;
}

.form-section {
  margin-bottom: 40px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.form-section h2 {
  font-size: 20px;
  color: #333;
  margin: 0 0 24px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #007bff;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group label {
  display: block;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #dc3545;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.char-count {
  position: absolute;
  right: 8px;
  bottom: 8px;
  font-size: 12px;
  color: #999;
}

.photo-upload {
  margin-top: 8px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.2s;
}

.upload-area:hover {
  border-color: #007bff;
}

.upload-content {
  color: #666;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.upload-content p {
  font-size: 16px;
  margin: 0 0 8px 0;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

.photo-preview {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-top: 16px;
}

.photo-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
}

.photo-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: rgba(0, 0, 0, 0.9);
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 40px;
  padding-top: 40px;
  border-top: 1px solid #eee;
}
</style>